package com.shawn.spring.boot.flowable.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.shawn.spring.boot.flowable.dto.VacationRequest;
import com.shawn.spring.boot.flowable.service.VacationService;
import com.shawn.spring.boot.flowable.util.JsonUtil;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.repository.Deployment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class VacationServiceImpl implements VacationService {

  @Autowired private RepositoryService repositoryService;

  @Autowired private RuntimeService runtimeService;

  @Autowired private TaskService taskService;

  @Override
  public void deployProcessDefinition() {
    Deployment deployment = repositoryService
        .createDeployment()
        .name("holidayRequest")
        .addClasspathResource("processes/holiday-request.bpmn20.xml")
        .key("holidayRequest")
        .deploy();
    System.out.println(deployment.getId());
  }

  @Override
  public void applyVacation(VacationRequest request) {
    runtimeService
        .createProcessInstanceBuilder()
        .processDefinitionId("holidayRequest:12:aa394de7-8744-11eb-ae0f-36c93d20b34a")
        .processDefinitionKey("holidayRequest")
        .variables(
            JsonUtil.fromJson(
                    JsonUtil.toJson(request).orElse("{}"),
                    new TypeReference<Map<String, Object>>() {})
                .orElse(new HashMap<>()))
        .start();
  }

  @Override
  public void approveHoliday(String taskId, boolean approved) {
    taskService
        .createTaskCompletionBuilder()
        .taskId(taskId)
        .variables(Collections.singletonMap("approved", approved))
        .complete();
  }

  @Override
  public void accept(String taskId) {
    taskService.complete(taskId);
  }
}
